<template>
  <div class="menu">

    <div class="btns">
      <el-button type="primary" @click="dialogVisible = true">添加</el-button>
      <el-button type="primary" @click="expandAll" >全部展开</el-button>
      <el-button type="primary">全部折叠</el-button>
    </div>

    <!-- 表格 -->
    <!-- default-expand-all -->
    <el-table
      :data="menuPermissions"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border 
      :default-expand-all="defaultExpandAll"
      :expand-row-keys="expandedRowKeys"
    >
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="type" label="类型">
        <template #default="{row}">
          <span>{{ row.type === 1 ? '菜单(页面)' : '功能(按钮)' }}</span>
          <!-- <span v-if="row.type === 1">菜单(页面)</span>
          <span v-else>功能(按钮)</span> -->
        </template>
      </el-table-column>
      <el-table-column prop="rule" label="规则" />
      <el-table-column prop="icon" label="操作">
        <template #default="{row}">
          <el-button type="primary" size="small" @click="handleedit(row)">编辑</el-button>
          <el-button type="danger" size="small"@click=handleDelet(row) >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加与修改的对话框 -->
    <el-dialog v-model="dialogVisible" :title="(permissionItem.id ? '修改' : '添加') + '菜单权限'" width="500">
      <el-form :model="permissionItem" label-width="80px" label-suffix=":">
        <el-form-item label="父级菜单">
          <el-tree-select
            v-model="permissionItem.pid"
            :data="parentMenus"
            check-strictly
            clearable
            :render-after-expand="false"
            placeholder="请选择父级菜单, 不选择则为顶级菜单"
          >
            <!-- <template #default="{ data: { name } }">
              {{ name }}
            </template> -->
          </el-tree-select> 
          <!-- <el-select v-model="permissionItem.pid" placeholder="请选择父级菜单">
            <el-option label="Zone No.1" value="shanghai" />
            <el-option label="Zone No.2" value="beijing" />
          </el-select> -->
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="permissionItem.name" placeholder="请输入权限名称"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-radio-group v-model="permissionItem.type">
            <el-radio :value="1">菜单(页面)</el-radio>
            <el-radio :value="2">功能(按钮)</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="规则">
          <el-input v-model="permissionItem.rule" placeholder="请输入权限规则"></el-input>
        </el-form-item>
        <el-form-item  label="排序">
          <el-input v-model="permissionItem.order" placeholder="请输入菜单排序"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="permissionItem.status" active-text="启用" inactive-text="禁用" active-color="#13ce66" inactive-color="#ff4949" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="hanleSaveMenu">
            {{ permissionItem.id ? "修改" : "添加"}}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref,computed,watch} from 'vue';
import { getAllMenuPermissions,addMenuPermission,updateMenuPermission,deleteMenuPermission } from "@/API/menu-permisssion"
import { transData } from "@/utils/index"
import {ElMessageBox} from "element-plus"

// 所有菜单的原始数据
const originPermissions = ref<IPermission[]>([])


// 所有的菜单权限树形数据
const menuPermissions = ref<IPermission[]>([])

// 查询所有菜单权限数据
const loadMenuPermissions = async() => {
  const res = await getAllMenuPermissions()
  originPermissions.value = res.list
  // 将查询到的数据转为树形结构
 const tree =  transData( res.list)
  console.log("tree:",tree)
  menuPermissions.value =tree
}
loadMenuPermissions()

// 编辑权限对话框显隐状态
const dialogVisible = ref<boolean>(false)

// 编辑对话框中的表单数据
const permissionItem = ref<IPermission>({
  id:"",
  pid:"",
  name:"",
  type:1,
  rule:"",
  parentId:"",
  status:true,
})

// 在树形选择框中的数据（父级菜单）结构
let parentMenus= computed(()=>{
  // 筛选出原始数据中所有菜单级权限
  let menus:any = originPermissions.value.filter(item=>item.type === 1)
  // 修改数据的结构
  menus = menus.map((menu:any)=>{
    return {
      pid:menu.pid,
      id:menu.id,
      value:menu.name,
      label:menu.name,
    }
  })
  // 转树形结构
    const tree = transData(menus)
    return tree
})


// 重置表达中的数据
const resetPermissionItem = () => {
  permissionItem.value = {
    id: '',
    name: '',
    pid: '',
    type: 1,
    rule: '',
    icon: '',
    status:true,
  } 
}

//监听对话框的显隐状态，如果关闭了，就重置表单数据
watch(dialogVisible,(newValue)=>{
  if(!newValue){
    resetPermissionItem()
  }

})


// 点击编辑(修改)按钮，，打开编辑对话框，回显表单数据
const handleedit = (row:IPermission)=>{
  console.log(permissionItem.value)
// 打开对话框
dialogVisible.value = true
// 回显表单数据
permissionItem.value = {...row}
}


// 
const hanleSaveMenu = async() => {
  console.log("保存菜单权限",permissionItem.value)

// 根据表单是否存在id来判断是添加还是修改
if(permissionItem.value.id){
  // 修改
  await updateMenuPermission(permissionItem.value)
}else{
  
  // 发送网络请求添加
//  const result = 
 await addMenuPermission(permissionItem.value)
//  console.log("添加结果",result)

}

//  关闭对话框
dialogVisible.value = false
// 重新加载数据
  loadMenuPermissions()
  // 重置表单中的数据
  resetPermissionItem()
}

// 处理点击删除按钮，显示确认对话框
const handleDelet = async (row:IPermission) =>{
try {
   // 显示确认对话框
   const confirm =  await ElMessageBox.confirm(
    '此操作将永久删除该菜单，是否继续？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    console.log("用户确认删除结果:",confirm)
    //如果用户确认删除，就发送网络请求，删除数据
    if(confirm ===  "confirm"){
      await deleteMenuPermission(row.id)
      // 重新加载菜单权限数据
      loadMenuPermissions()
    }
}catch(error){
 console.log("点击了取消...",error)
}

}

// 全部折叠
// 定义表格的初始值为一个空数组

 let  expandedRowKeys:any= ref([]);
const defaultExpandAll = ref(false);

const expandAll = () => {
      defaultExpandAll.value = true;
    };

</script>

<style lang="less" scoped>
.menu{
  padding: 12px;
  .btns{
    margin-bottom: 12px;
  }
}
</style>
